<template>
  <div>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <el-form ref="form" :model="form" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
    <el-form-item label="登录名称" >
      <el-input  :disabled="true" :value="$store.state.user.user.username" :style="{ width: '400px' }" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="用户昵称" prop="nickname">
      <el-input v-model="form.nickname" :style="{ width: '400px' }" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="用户邮箱" prop="email">
      <el-input v-model="form.email" :style="{ width: '400px' }"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onsubmit">提交修改</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
</el-form>
  </el-card>
</div>
</template>

<script>
import { updateUserInfoAPI } from '@/api/user'
export default {
  name: 'user-info',
  data () {
    const checkEmail = (rule, value, cb) => {
      const reg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      if (!reg.test(value)) {
        cb(new Error('请输入正确的邮箱格式'))
      } else {
        cb()
      }
    }
    return {
      // 默认表单数据
      defaultForm: {
        nickname: '',
        email: ''
      },
      form: {
        id: this.$store.state.user.user.id,
        nickname: '',
        email: ''
      },
      rules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 1, max: 10, message: '昵称长度为1-10', trigger: ['blur', 'change'] }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }

        ]
      }
    }
  },
  methods: {
    onsubmit () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          await updateUserInfoAPI(this.form)
          this.$message.success('更新成功')
          this.$store.dispatch('user/getUser') // 重新获取用户信息进行渲染
          this.resetForm()
        } else {
          this.$message.error('提交失败')
        }
      })
    },
    resetForm () {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>

</style>
